package com.xnx3.kefu.inset.controller;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.Lang;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ApplicationPropertiesUtil;
import com.xnx3.j2ee.util.CacheUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.SessionUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.json.JSONUtil;
import com.xnx3.net.HttpResponse;
import com.xnx3.net.HttpUtil;
import com.xnx3.wangmarket.plugin.api.Global;
import com.xnx3.wangmarket.plugin.api.controller.BaseController;
import com.xnx3.wangmarket.plugin.api.entity.InsetUser;
import com.xnx3.wangmarket.plugin.api.vo.UserVO;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.kefu.core.util.TokenUtil;
import net.sf.json.JSONObject;

/**
 * 第三方系统在chat聊天时的相关
 * @author 管雷鸣
 * @deprecated
 */
@Controller(value="InsetChatController")
@RequestMapping("/kefu/inset/")
public class LoginController extends BaseController {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private KefuService kefuService;

	/**
	 * 通过别人第三方系统的token(或sessionid)，来换取对应自己客服平台的user，将这个user变为登录状态
	 * @param otherToken 最大不超过64位字符串，这是第三方平台的token，用它来去第三方平台拉取用户信息
	 * @param token 客服平台本身js产生的token
	 * @return 
	 */
	@ResponseBody
	@RequestMapping(value="login${api.suffix}", method = RequestMethod.POST)
	public UserVO login(HttpServletRequest request,Model model,
			@RequestParam(value = "otherToken", required = false, defaultValue = "") String otherToken,
			@RequestParam(value = "token", required = false, defaultValue = "") String token){
		UserVO vo = new UserVO();
		
		
//		if(true){
//			User user = new User();
//			com.xnx3.j2ee.entity.User userEntity = sqlCacheService.findById(com.xnx3.j2ee.entity.User.class, 1);
//			user.setUser(userEntity);
//			user.setNickname("test user");
//			user.setHead("https://res.weiunity.com/kefu/images/head.png");
//			vo.setUser(user);
		
//			//token绑定uid
//			TokenBind.bind(token, user);
//			ConsoleUtil.log("chat - token bind,  token:"+token+", user:"+user);
//			return vo;
//		}
//		
		//先判断一下token是否被缓存了
		String key = Global.CACHE_OTHER_TOKEN.replace("{token}", otherToken);
		ConsoleUtil.log(key);
		Object obj = CacheUtil.get(key);
		if(obj != null){
			//缓存中发现 otherToken，那么直接返回就可以了
			vo = (UserVO)obj;
			ConsoleUtil.log("cache uservo:"+vo.toString());
		}else{
			//缓存中没有发现，拿otherToken 去第三方接口中换取用户的身份信息
			String getUserApi = ApplicationPropertiesUtil.getProperty("kefu.otherSystem.getUserApi");
			HttpUtil httpUtil = new HttpUtil();
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", otherToken);
			HttpResponse hr = httpUtil.post(getUserApi, params);
			if(hr.getCode() != 200){
				vo.setBaseVO(UserVO.FAILURE, "三方平台http code响应异常");
				return vo;
			}
			if(hr.getContent() == null){
				vo.setBaseVO(UserVO.FAILURE, "三方平台http content响应异常");
				return vo;
			}
			JSONObject json = JSONObject.fromObject(hr.getContent());
			if(!JSONUtil.getString(json, "result").equals("1")){
				//失败
				vo.setBaseVO(UserVO.FAILURE, JSONUtil.getString(json, "info"));
				return vo;
			}
			System.out.println(json.toString());
			ChatUserBean chatUser = new ChatUserBean();
			
			JSONObject userJson = json.getJSONObject("data").getJSONObject("userVO").getJSONObject("user");
			String otherUserid = JSONUtil.getString(userJson, "id");
			
			//判断一下这个用户在 Inset_user 中是否有对应用户了
			InsetUser insetUser = sqlCacheService.findAloneByProperty(InsetUser.class, "otherUserid", otherUserid);
			if(insetUser == null){
				//创建这个用户
				com.xnx3.j2ee.entity.User createUserEntity = new com.xnx3.j2ee.entity.User();
				createUserEntity.setNickname(otherUserid+"");
				createUserEntity.setUsername(Lang.uuid());
				createUserEntity.setPassword(Lang.uuid());
				createUserEntity.setHead("https://res.weiunity.com/kefu/images/head.png");
				BaseVO createUserVO = userService.createUser(createUserEntity, request);
				if(createUserVO.getResult() - BaseVO.FAILURE == 0){
					vo.setBaseVO(UserVO.FAILURE, vo.getInfo());
					return vo;
				}
				
				chatUser.setUser(createUserEntity);
				
				insetUser = new InsetUser();
				insetUser.setOtherUserid(otherUserid);
				insetUser.setUserid(createUserEntity.getId());
				sqlService.save(insetUser);
				
				vo.setOtherUserId(otherUserid+"");
			}else{
				//已经创建过了，那么久查出来
				com.xnx3.j2ee.entity.User cacheUser = sqlCacheService.findById(com.xnx3.j2ee.entity.User.class, insetUser.getUserid());
				if(cacheUser == null){
					vo.setBaseVO(UserVO.FAILURE, "客服平台关联的 User 不存在");
					return vo;
				}
				//查出本平台对应的，第三方平台的userid
				InsetUser insetUserCache = sqlCacheService.findAloneByProperty(InsetUser.class, "userid", cacheUser.getId());
				if(insetUserCache == null){
					vo.setBaseVO(UserVO.FAILURE, "客服平台关联的三方平台的 user.id 不存在");
					return vo;
				}
				
				chatUser.setUser(cacheUser);
				vo.setOtherUserId(insetUserCache.getOtherUserid());
				ConsoleUtil.log("已经创建过了，那么久查出来 : "+vo.toString());
			}
			vo.setUser(chatUser);
			
			//缓存 user bean
			CacheUtil.set(key, vo);
		}
		
		//token绑定uid
		TokenUtil.bind(token, vo.getUser());
//		ConsoleUtil.log("token bind -- "+token+":"+token+", user:"+vo.getUser().toString());
		
		//登录成功后，将当前sessionid进行缓存，以便可以根据sessionid直接取User信息
		com.xnx3.kefu.core.util.SessionUtil.setActiveUserForNotRedis(request.getSession().getId(), SessionUtil.getActiveUser());
		
		
		return vo;
	}
	
}
